package com.sunyard.base.http

import android.util.Log
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

abstract class BaseRetrofitFactory {

    private val retrofit: Retrofit
    private var retrofitBuilder: Retrofit.Builder
    private var connectTimeUnit = setConnectTimeUnit()
    private var readTimeout = setReadTimeOut()
    private var baseUrl = setBaseUrl()
    private var okHttpClientBuilder: OkHttpClient.Builder


    init {
        val gson = Gson().newBuilder()
            .setLenient()
            .serializeNulls()
            .create()
        okHttpClientBuilder = initOkhttpClientBuilder()
        addInterceptor(okHttpClientBuilder)

        retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClientBuilder.build())

        addConverterFactory(retrofitBuilder)


        retrofit = retrofitBuilder.build()
    }

    abstract fun addInterceptor(okHttpClientBuilder: OkHttpClient.Builder)
    abstract fun addConverterFactory(retrofitBuilder: Retrofit.Builder)
    open fun setConnectTimeUnit() = 5L
    open fun setReadTimeOut() = 5L
    open fun setBaseUrl() = "https://www.baidu.com/"

    private fun initOkhttpClientBuilder() =
        OkHttpClient.Builder()
            .connectTimeout(connectTimeUnit, TimeUnit.SECONDS)
            .readTimeout(readTimeout, TimeUnit.SECONDS)
            .addInterceptor(initLogInterceptor())

    /*
    * 日志拦截器
    * */
    private fun initLogInterceptor(): HttpLoggingInterceptor {

        val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                Log.e("Retrofit", message)
            }
        })

        interceptor.level = HttpLoggingInterceptor.Level.BODY

        return interceptor
    }


    /*
    * 具体服务实例化
    * */
    fun <T> getService(service: Class<T>): T {

        return retrofit.create(service)
    }
}



